package me.shurufa.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;

import butterknife.Bind;
import cn.finalteam.okhttpfinal.HttpRequest;
import me.shurufa.R;
import me.shurufa.bean.Notice;
import me.shurufa.bean.NoticeInfo;
import me.shurufa.event.EventObject;
import me.shurufa.net.API;
import me.shurufa.net.RequestParams;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.NoticeInfoResp;
import me.shurufa.response.SendCommentResp;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Utils;
import me.shurufa.widget.commentbar.SimpleOnSendButtonClickListener;
import me.shurufa.widget.commentbar.SimpleSendCommentBar;

/**
 * Create by andy
 * Description: 消息回复界面
 */
public class NoticeMessageReplyActivity extends BaseActivity implements View.OnClickListener {

    /**
     * 书摘的评论类型 跳转到书摘详情界面
     */
    private static final String TYPE_DIGEST = "excerpt_comment";
    /**
     * 书评的评论类型 跳转到书评详情界面
     */
    private static final String TYPE_BOOKCOMMENT = "book_comment";

    @Bind(R.id.right_text)
    TextView rightText;
    @Bind(R.id.toolbar_title)
    TextView titleText;
    @Bind(R.id.iv_avatar)
    ImageView iv_avatar;

    @Bind(R.id.tv_uname)
    TextView tv_uname;
    @Bind(R.id.tv_comment_content)
    TextView tv_comment_content; // 回复内容
    @Bind(R.id.tv_src_digest)
    TextView tv_src_digest;      // 原书摘内容
    @Bind(R.id.iv_src_digest)
    ImageView iv_src_digest;     // 原书摘图片

    @Bind(R.id.tv_create_time)
    TextView tv_create_time;     // 时间
    @Bind(R.id.scb_comment_bar)
    SimpleSendCommentBar sendCommentBar;

    private NoticeInfo mNoticeInfo;
    private Context mContext;
    private Notice mNotice;
    private String mID;
    private String mCommentId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        try {
            activity_layout_res = R.layout.activity_message_notice_reply;
            super.onCreate(savedInstanceState);
            parseArguments();
            initUI();
            initData();
        } catch (Exception e) {
            Utils.showToast(R.string.sys_err);
        }
    }

    public static void initArguments(Intent in, Notice notice) {
        in.putExtra(Constants.ARG_COMMENT_ID, notice);
    }

    private void parseArguments() {
        mNotice = (Notice) getIntent().getSerializableExtra(Constants.ARG_COMMENT_ID);
        mID = String.valueOf(mNotice.id);
        mCommentId = String.valueOf(mNotice.rid);
    }

    private void initUI() {
        mContext = this;
        titleText.setText(getString(R.string.message));

        rightText.setText(getString(R.string.reply));
        rightText.setVisibility(View.VISIBLE);
        rightText.setOnClickListener(this);
        tv_src_digest.setOnClickListener(this);
        iv_src_digest.setOnClickListener(this);

        sendCommentBar.setOnSendButtonClickListener(new SimpleOnSendButtonClickListener() {
            @Override
            public void onSend(String commentId, String content) {
                sendCommentBar.clearFocus();
                Utils.closeInputMethod(mContext, sendCommentBar.getEditText());
                reqReplyComment(commentId, content);
            }
        });
    }

    private void initData() {
        if (!TextUtils.isEmpty(mID)) {
            reqNoticeMessageById(mID);
        }
    }

    // 请求数据
    private void reqNoticeMessageById(final String mCommentId) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("id", mCommentId);
        HttpRequest.post(API.GET_NOTICE_INFO, params, new HttpCallback<NoticeInfoResp>() {

            @Override
            public void onRespSuccess(NoticeInfoResp noticeInfoResp) {
                try {
                    handleUI(noticeInfoResp.data);
                } catch (Exception e) {
                }
            }

            @Override
            public void onRespFailure(NoticeInfoResp noticeInfoResp) {

            }
        });

    }

    /**
     * 处理刷新UI
     *
     * @param data
     */
    private void handleUI(NoticeInfo data) {
        mNoticeInfo = data;

        tv_src_digest.setText(data.content_info.content_info);
        if (data != null && data.content_info != null && !TextUtils.isEmpty(data.content_info.screenshot)) {
            tv_src_digest.setVisibility(View.GONE);
            iv_src_digest.setVisibility(View.VISIBLE);
            // 图片书摘
            Glide.with(mContext).load(data.content_info.screenshot + Constants.THUMB_SUFFIX).centerCrop()
                    .placeholder(R.drawable.ic_placeholder_digest_image).error(R.drawable.ic_placeholder_digest_image).into(iv_src_digest);
        }


        tv_uname.setText(data.f_name);
        tv_create_time.setText(Utils.getFormatTime(data.created_at));

        SpannableString ss = new SpannableString(mNotice.msg + ": " + data.content);
        ss.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.gray_text))
                , 0
                , mNotice.msg.length() + ": ".length()
                , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_comment_content.setText(ss);

        // avatar
        if (!TextUtils.isEmpty(data.avatar)) {
            Glide.with(mContext).load(data.avatar + Constants.THUMB_SUFFIX_AVATAR).asBitmap().centerCrop().into(new BitmapImageViewTarget(iv_avatar) {
                @Override
                protected void setResource(Bitmap resource) {
                    super.setResource(resource);
                    RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(mContext.getResources(), resource);
                    circularBitmapDrawable.setCircular(true);
                    iv_avatar.setImageDrawable(circularBitmapDrawable);
                }
            });
        } else {
            iv_avatar.setImageResource(R.drawable.ic_def_avatar);
        }
    }


    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.right_text:
                sendCommentBar.setVisibility(View.VISIBLE);
                sendCommentBar.requestFocus();
                sendCommentBar.setCommentId(mCommentId);
                Utils.showSoftkeyboard(mContext, sendCommentBar.getEditText());
                break;
            case R.id.tv_src_digest:
            case R.id.iv_src_digest:
                // 跳转到详情页 判断是书摘还是书评
                if (TYPE_DIGEST.equals(mNoticeInfo.item_type)) {
                    try {
                        Intent in = new Intent(this, CommentDetailActivity.class);
                        String bookName = mNoticeInfo.content_info.title;
                        long id = Long.valueOf(mNoticeInfo.content_info.id);
                        CommentDetailActivity.initArguments(in, bookName, id, Constants.TYPE_COMMENT_EXCERPT);
                        startActivity(in);
                        return;
                    } catch (Exception e) {
                        Utils.showToast(R.string.sys_err);
                    }
                }

                if (TYPE_BOOKCOMMENT.equals(mNoticeInfo.item_type)) {
                    try {
                        Intent in = new Intent(this, CommentDetailActivity.class);
                        String bookName = mNoticeInfo.content_info.title;
                        long id = Long.valueOf(mNoticeInfo.content_info.id);
                        CommentDetailActivity.initArguments(in, bookName, id, Constants.TYPE_COMMENT_BOOK_COMMENT);
                        startActivity(in);
                        return;
                    } catch (Exception e) {
                        Utils.showToast(R.string.sys_err);
                    }
                }
                break;
        }
    }

    @Override
    public void onEventMainThread(Intent intent) {
    }

    public void onEventMainThread(EventObject object) {
    }

    /**
     * 创建评论 回复评论
     * @param commentId 评论id
     * @param content   内容
     */
    private void reqReplyComment(String commentId, final String content) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("id", commentId);
        params.addFormDataPart("content", content);

        HttpRequest.post(API.REPLY_COMMENT, params, new HttpCallback<SendCommentResp>() {
            @Override
            public void onRespSuccess(SendCommentResp resp) {
                sendCommentBar.getEditText().setText(null);
                sendCommentBar.setVisibility(View.GONE);
                Utils.showToast("回复成功");
            }

            @Override
            public void onRespFailure(SendCommentResp resp) {

            }
        });
    }

    @Override
    public void onBackPressed() {
        if (sendCommentBar.getVisibility() == View.VISIBLE) {
            sendCommentBar.getEditText().clearFocus();
            sendCommentBar.setVisibility(View.GONE);
        } else {
            super.onBackPressed();
        }

    }
}
